import {Component, OnDestroy, OnInit} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Subscription, timer} from 'rxjs';

import {Metric} from '../../model/Metric';

import * as Highcharts from 'highcharts';
import theme from 'highcharts/themes/dark-unica';

theme(Highcharts);

@Component({
  selector: 'app-r2dbcPool',
  templateUrl: './r2dbcPool.component.html',
  styleUrls: ['./r2dbcPool.component.css']
})
export class R2dbcPoolComponent implements OnInit, OnDestroy {

  Highcharts: typeof Highcharts = Highcharts;

  r2dbcPool_chart: any;
  r2dbcPool_chartCallback: any;
  r2dbcPool_chartOptions: Highcharts.Options = {
    chart: {
      type: 'spline',
    },
    time: {
      useUTC: false,
    },
    title: {
      "text": '连接池'
    },
    xAxis: {
      type: 'datetime',
      dateTimeLabelFormats: {
        day: '%m-%d',
      },
      labels: {
        overflow: 'justify',
      },
    },
    yAxis: {
      allowDecimals: false,
      title: {
        text: "数量"
      }
    },
    tooltip: {
      headerFormat: '<b>{point.x:%Y-%m-%d %H:%M:%S}</b><br>',
      pointFormat: '{point.y:.2f}',
    },
    plotOptions: {
      spline: {
        marker: {
          enabled: true
        }
      }
    },
    series: [{
      type: 'spline',
      name: "最大连接数",
      data: []
    },
      {
        type: 'spline',
        name: "使用连接数",
        data: []
      },
      {
        type: 'spline',
        name: "等待连接数",
        data: []
      }]
  };


  subscribe = Subscription.EMPTY;

  constructor(private httpClient: HttpClient) {
    const self = this;
    this.r2dbcPool_chartCallback = (chart: Highcharts.Chart) => {
      self.r2dbcPool_chart = chart;
    }
  }

  ngOnInit() {
    const source = timer(1000, 30 * 1000);
    this.subscribe = source.subscribe(val => this.getMessage());
  }

  ngOnDestroy() {
    this.subscribe.unsubscribe();
  }

  getMessage() {
    let url = '/monitor';
    this.httpClient.get(url).subscribe((data: any) => {
      let metrics: Metric[] = data;
      metrics.forEach(metric => {
        if (metric.name === 'r2dbc.pool.allocatedSize') {
          this.r2dbcPool_chart.series[0].addPoint(metric.datapoints[0], true, false);
        } else if (metric.name === 'r2dbc.pool.acquiredSize') {
          this.r2dbcPool_chart.series[1].addPoint(metric.datapoints[0], true, false);
        } else if (metric.name === 'r2dbc.pool.pendingAcquireSize') {
          this.r2dbcPool_chart.series[2].addPoint(metric.datapoints[0], true, false);
        }
      });
    });
  }

}
